<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Crypt;
use DB;

class AdminController extends Controller
{
   	public function add(){
   		return view('admin.admin.add');
   	}

   	public function insert(Request $request)
   	{
   		$this->validate($request,[
   			'name' => 'required|min:6|max:18',
   			'password' => 'required',
   			'repassword' => 'same:password',
   			'email' => 'email',
    		'phone' => 'digits:11',
   			'pic' => 'image|max:2048',
   			],[
   			'name.required' => '管理员姓名不能为空',
   			'email.required' => '邮箱不能为空',
   			'phone.required' => '手机号不能为空',
   			'name.min' => '管理员姓名至少6位',
   			'name.max' => '管理员姓名最多8位',
   			'password.required' => '密码不能为空',
   			'repassword.same' => '两次密码不一致',
   			'email.email' => '请输入正确的邮箱',
   			'phone.digits' => '请输入11位手机号码',
   			'pic.image' => '上传的必须是一张图片',
   			'pic.max' => '图片最大为2MB',
   			]);

   		$data = $request -> except('_token','repassword');

   		$adminData['name'] = $data['name'];
   		$adminData['email'] = $data['email'];
   		$adminData['phone'] = $data['phone'];
   		//处理密码字段
   		$adminData['password'] = Crypt::encryptString($data['password']);
   		if($request -> hasFile('pic'))
   		{
   			if($request -> file('pic') -> isValid())
   			{
   				 //处理头像
		   		$extension = $request -> file('pic') -> getClientOriginalExtension();
		   		// echo $extension; 

		   		$filename = mt_rand(10000000,99999999).'.'.$extension;
		   		$dir = './uploads/avatar/';

		   		$request -> file('pic') -> move($dir, $filename);

		   		$adminInfoData['pic'] = '/uploads/avatar/'.$filename;
   			}
   		}else
   		{
   			$adminInfoData['pic'] = '/uploads/avatar/default.jpg';
   		}
   		
   		$adminData['token'] = str_random(50);
   		$adminData['airline'] = 0;
   		$adminData['status'] = 0;

   		$time = Date('Y-m-d H:i:s');
   		$adminData['created_at'] = $time;
   		$adminData['updated_at'] = $time;
   		
   		//添加数据
   		$adminId = DB::table('admins') -> insertGetId($adminData);

   		if($adminId)
   		{
   			$adminInfoData['admin_id'] = $adminId;
   			$adminInfoData['created_at'] = $time;
   			$adminInfoData['updated_at'] = $time;

   			$res = DB::table('admins_info') -> insert($adminInfoData);

   			if($res)
   			{
   				return redirect('/admin/admin/index') -> with(['info' => '添加成功']);
   			}else
   			{
   				return back() -> with(['info' => '添加失败']);
   			}
   		}

   	}


	//index
	public function index(Request $request)
	{
		$num = $request -> input('num',10);
		$keywords = $request -> input('keywords','');


		$data = DB::table('admins') 
		-> select('admins.*','admins_info.pic')
		-> leftJoin('admins_info','admins.id','=','admins_info.admin_id')
		-> where('name','like','%'.$keywords.'%')
		-> paginate($num);
		// dd($data);	
		return view('admin.admin.index',['data' => $data, 'request' => $request -> all()]);
	} 

	//ajax 修改管理员姓名
	public function changeName(Request $request)
    {	
    	$id = $request -> id;
    	$name = $request -> name;

    	$res = DB::table('admins') -> where('id', $id) -> update(['name' => $name]);
    	
    	if($res)
    	{
    		return 1;
    	}else
    	{
    		return 0;
    	}

    	// return 'abc';
    }

    public function edit($id)
    {

    	$data = DB::table('admins') 
		-> select('admins.*','admins_info.pic')
		-> leftJoin('admins_info','admins.id','=','admins_info.admin_id')
		-> where ('admins.id', '=',$id)
		-> first();
    	return view('admin.admin.edit',['data' => $data]);
    }

    // update  更新方法
    public function update(Request $request)
    {	
    	//一个验证的方法
    	$this -> validate($request, [
    		'name' => 'required|min:6|max:18',
   			'email' => 'email',
    		'phone' => 'digits:11',
   			'pic' => 'image|max:2048',
   			],[
   			'name.required' => '管理员姓名不能为空',
   			'email.required' => '邮箱不能为空',
   			'phone.required' => '手机号不能为空',
   			'name.min' => '管理员姓名至少6位',
   			'name.max' => '管理员姓名最多8位',
   			'email.email' => '请输入正确的邮箱',
   			'phone.digits' => '请输入11位手机号码',
   			'pic.image' => '上传的必须是一张图片',
   			'pic.max' => '图片最大为2MB',
    	]);

    	$id = $request -> id;

    	$data = $request -> except('_token','id','pic');

    	
    	if($request -> hasFile('pic'))
    	{
    		if($request -> file('pic') -> isValid())
    		{
    			//处理头像
		    	// getClientOriginalExtension()    extension()
		    	$extension = $request -> file('pic') -> getClientOriginalExtension();
		    	// echo $extension;
		    	$filename = mt_rand(1000000,9999999).'.'.$extension;
		    	$dir = './uploads/avatar/';

		    	$request -> file('pic') -> move($dir,$filename);//storeAs
    			$adminInfoData['pic'] = '/uploads/avatar/'.$filename;
    			//获取原来的图片地址
    			$oldpic = DB::table('admins_info') -> where('admin_id',$id) -> first() -> pic;
    			if(!empty($oldpic))
    			{
    				if($oldpic != '/uploads/avatar/default.jpg')
    				{	

    					// if($oldpic == '/' || $oldpic =='./')//自己加的判断防误删
    					// 	{
    					// 		return;
    					// 	}
    					if(file_exists('.'.$oldpic))
    					{
    						unlink('.'.$oldpic);
    					}
    				}
    			}

    			DB::table('admins_info') ->where(['admin_id' => $id]) -> update($adminInfoData);
    			// var_dump($adminInfoData);
    		}
    	}else
    	{
    		$adminInfoData['pic'] = '/uploads/avatar/default.jpg';
    	}
    	//修改
    	$res = DB::table('admins') -> where('id',$id) ->update($data);
    	
    	if($res)
    	{
    		return redirect('/admin/admin/index') -> with(['info' => '修改成功']);
    	}else
    	{
    		return back() -> with(['info' => '修改失败']);
    	}
    }
    public function delete($id)
    {
    	$pic = DB::table('admins_info') -> where('id',$id) ->first() ->pic;
    	$res = DB::table('admins') -> where('id',$id) -> delete();
    	$oldPic = DB::table('admins_info') -> where('admin_id',$id) -> first() -> pic;
    	if($res)
    	{
    		DB::table('admins_info') ->where('admin_id',$id) -> delete();

    		if(!empty($oldPic))
			{
				if($oldPic != '/uploads/avatar/default.jpg')
				{	

					if(file_exists('.'.$oldPic))
					{
						unlink('.'.$oldPic);
					}
				}
			}
    	}
		if($res)
		{
    		return redirect('/admin/admin/index') -> with(['info' => '删除成功']);
    	}else
    	{
    		return back() -> with(['info' => '删除失败']);
    	}  		

    }
}
